<template>
  <view class="home-page">
    <Address
      class="location-row"
      :currentAddress="currentAddress"
      @getAddress="getAddress"
    ></Address>
    <u-search
      class="search-sticky"
      :placeholder="'大家都在搜: ' + topSearchProfessor"
      :showAction="false"
      @search="redirectToSearch"
      v-model="searchProfessor"
    ></u-search>
    <SlideShow :topList="topList"></SlideShow>
    <BranchRow :branchList="branchList"></BranchRow>
    <u--text
      text="精选推荐"
      size="15"
      bold
    ></u--text>
    <ProfessorCard
      v-for="(professor, index) in professorList"
      :key="'professor' + index"
      :professor="professor"
    ></ProfessorCard>
  </view>
</template>

<script>
  import { map, professor } from "@/api";
  import { showMessage } from "@/common/utils";
  import { ERROR_TYPE } from "@/common/constants";
  import { ROUTE_PATHS } from "@/router/routes";
  import { debounce } from "lodash";

  export default {
    data() {
      return {
        /**
         * top3轮播图
         * @type {object}
         * @property {Array} top 轮播图数据
         * @property {string} top.name 轮播图名称
         * @property {string} top.area 轮播图领域
         * @property {Array} image 轮播图图片
         */
        topList: { top: [{ name: "", area: "" }], image: [] },
        /**
         * branch部门
         * @type {Array}
         */
        branchList: [{ name: "", image: "" }],
        /**
         * top10精选推荐
         * @type {Array}
         */
        professorList: [],
        /**
         * 热搜专家
         * @type {String}
         */
        topSearchProfessor: "",
        /**
         * 随机热搜专家计时器
         */
        intervalId: {},
        /**
         * 当前地理位置精确到街道
         * @type {String}
         */
        currentAddress: "定位中 ......",
        /**
         * 搜索关键词
         * @type {String}
         */
        searchProfessor: "",
      };
    },
    async onLoad() {
      await this.init();
    },
    async onPullDownRefresh() {
      await this.init();
      uni.stopPullDownRefresh();
    },
    methods: {
      /**
       * 获得top3轮播图数据
       */
      async getTop3() {
        try {
          const response = await professor.getProfessorTop3List();
          this.topList.top = response.data;
          // 获取热搜专家
          this.getSearchProfessor(this.topList.top);
          // 没有图，暂时使用静态图代替
          this.topList.image = this.topList.top.map(
            (_, i) => `/static/images/top3back${i}.png`
          );
        } catch (error) {
          if (error.type === ERROR_TYPE.NETWORK) {
            return;
          }
          showMessage(error.msg || "获取专家TOP3数据失败", false);
        }
      },
      /**
       * 获得branch部门列表数据，暂时是假数据
       */
      getBranch() {
        const branchList = ["研发", "网络技术", "黑客技术", "AI算法"];
        // 没有图，暂时使用静态图代替
        this.branchList = branchList.map((name, i) => ({
          name: name,
          image: `/static/images/branch${i}.png`,
        }));
      },

      /**
       * 获得top10精选数据
       */
      async getTop10() {
        try {
          const response = await professor.getProfessorTop10List();
          this.professorList = response.data;
        } catch (error) {
          if (error.type === ERROR_TYPE.NETWORK) {
            return;
          }
          showMessage(error.msg || "获取专家TOP10数据失败", false);
        }
      },
      /**
       * 初始化getAddress,防抖函数
       */
      initDebounceGetAddress() {
        //	getAddress获得位置精确到街道
        this.getAddress = debounce(() => {
          uni.getLocation({
            type: "wgs84",
            geocode: true,
            success: async (res) => {
              const location = {
                longitude: res.longitude,
                latitude: res.latitude,
              };
              const response = await map.getAddressByLocation(location);
              this.currentAddress = response.result?.address;
            },
            fail: (err) => {
              this.currentAddress = "获取位置失败";
            },
          });
        }, 500);
      },
      /**
       * 随机获得热搜专家
       * @param {Array} professorList
       */
      getSearchProfessor(professorList) {
        // TODO 之后应该从后端调用接口返回热搜词，暂时从top3随机获取
        let index = Math.floor(Math.random() * professorList.length);
        this.topSearchProfessor = professorList[index].name;
      },
      /**
       * 跳转页面到search,传递搜索关键词
       * @param {String} searchProfessor
       */
      redirectToSearch(searchProfessor) {
        this.$Router.push({
          path: ROUTE_PATHS.SEARCH,
          query: {
            searchProfessor: searchProfessor,
          },
        });
      },
      /**
       * 初始化
       */
      async init() {
        await this.getTop3();
        this.getBranch();
        await this.getTop10();
        this.initDebounceGetAddress();
        this.getAddress();
      },
    },
  };
</script>

<style lang="scss" scoped>
  .home-page {
    display: flex;
    flex-direction: column;
    padding: 0 var(--margin-base);
    gap: var(--margin-mini);

    .location-row {
      display: flex;
      align-items: center;
      height: 44px;
    }

    .search-sticky {
      background-color: white;
    }
  }
</style>
